<?php
//修改历史
//修改时间：2018/1/19
//修改人：lizenan
//修改功能：【后台需求】将原本SKU的系列号转移至商品基础资料维护中
//任务ID：469

//修改时间：2018/1/19
//修改人：lizenan
//修改功能：【后台需求】关键词维护改进
//任务ID：430

//修改时间：2018/3/1
//修改人：lizenan
//修改功能：【后台需求】商品查询增加操作日志
//任务ID：525
namespace backend\controllers;
use Yii;
use common\helps;
use common\helps\tools;
use backend\models\SysSeq;
use yii\web\AdminController;
use backend\models\GoodsTag;
use backend\models\GoodsSpec;
use backend\models\GoodsSale;
use backend\models\GoodsList;
use backend\models\UploadForm;
use backend\models\GoodsBrand;
use backend\models\GoodsSource;
use common\models\CustFavorite;
use backend\models\GoodsKeyword;
use backend\models\GoodsRelation;
use backend\models\GoodsCategory;
use backend\models\GoodsListEdit;
use backend\models\GoodsSaleEdit;
use backend\models\GoodsSpecGroup;
use backend\models\GoodsSourceEdit;
use common\helps\getActivityMessage;
use backend\models\GoodsTagRelation;
use backend\models\GoodsCateRelation;
use backend\models\GoodsSpecRelation;
use backend\models\GoodsCategoryBrRelation;
// use backend\models\GoodsIdentification;
use common\helps\redisHelper;
use yii\web\NotFoundHttpException;
use common\helps\getCoupon;
use backend\models\GoodsMarkingImg;
use backend\models\GoodsLog;
use backend\models\NavigationIdentification;
use backend\models\GoodsNavigationIdentificationrelationEdit;
use backend\models\GoodsNavigationIdentificationrelation;

class GoodsController extends AdminController{
    public $layout = false;
    //业务关键字
    public $service = 'Goods';

    public function actionIndex(){
        //关键字
        $keyword = GoodsKeyword::find()->select('name')->where('use_flg=1')->orderBy('sort asc')->asArray()->all();
        //一级分类列表
        $where = ['use_flg'=>1,'parent_id'=>0];
        $category_list = GoodsCategory::find()->where($where)->asArray()->all();

        //二级分类列表
        $map = ['and',['use_flg'=>1],['!=','parent_id',0]];
        $category_child_list = GoodsCategory::find()->where($map)->select('id,category_name,parent_id')->asArray()->all();
        $list = array();
        foreach($category_child_list as $value){
            $list[$value['parent_id']][] = $value;
        }

        //品类列表
        $tag_where = ['use_flg'=>1];
        $tag = GoodsCateRelation::find()->where($tag_where)->select('category_id,tag_id,tag_name')->asArray()->all();
        $tag_list = array();
        foreach($tag as $value){
            $tag_list[$value['category_id']][] = $value;
        }
        //品牌列表
        $brand_where = ['use_flg'=>1];
        $brand = GoodsCategoryBrRelation::find()->where($brand_where)->select('category_id,brand_id,brand_name')->asArray()->all();
        $brand_list = array();
        foreach($brand as $value){
            $brand_list[$value['category_id']][] = $value;
        }

        //规格
        $spec_where = ['use_flg'=>1];
        $spec_group_list = GoodsSpecGroup::find()->where($spec_where)->select('id,spec_group_name,spec_type')->asArray()->all();
        $spec_list = GoodsSpec::find()->select('id,spec_name,spec_group_id,spec_val')->where($spec_where)->asArray()->all();
        foreach($spec_group_list as &$value){
            $value['child_list'] = array();
            foreach($spec_list as $val){
                if($value['id'] == $val['spec_group_id']){
                    $value['child_list'][] = $val;
                }
            }
        }
        //商品标识
//         $goods_identification = GoodsIdentification::find()->where('type=1 and use_flg=1')->asArray()->all();
        //商品导航标识
        $nav_identification = NavigationIdentification::find()->where('is_show=1')->asArray()->all();
        $nav_identification_list = [];
        if (is_array($nav_identification) && count($nav_identification) > 0){
            foreach ($nav_identification as $val){
                if ($val['parent_id'] === '0'){
                    $nav_identification_list[$val['id']] = $val;
                }else{
                    $nav_identification_list[$val['parent_id']]['son'][] = $val;
                }
            }
            $nav_identification_list = array_values($nav_identification_list);
        }
        //商品打标图片
        $mark_img = GoodsMarkingImg::find()->where('use_flg='.GoodsMarkingImg::STATUS_ENABLE)->orderBy('sort asc')->asArray()->all();
        $model = new UploadForm();
        //操作日志
        $this->saveLog($this->service,'商品查询','VIEW','');
        return $this->render('index',[
            'keyword'=>$keyword,
            'category_list'=>$category_list,
            'category_child_list'=>json_encode($list,true),
            'brand_list'=>json_encode($brand_list,true),
            'tag_list'=>json_encode($tag_list,true),
            'spec_group_list'=>$spec_group_list,
//             'goods_identification'=>$goods_identification,
            'nav_identification_list'=>$nav_identification_list,
            'model'=>$model,
            'mark_img'=>$mark_img
        ]);
    }

    //商品列表
    public function actionGetGoodsList(){
        $data = Yii::$app->request->post();
        $category_list = GoodsCategory::find()->select('id,category_name')->asArray()->all();
        $goods_category_list = array();
        foreach($category_list as $value){
            $goods_category_list[$value['id']]['category_name'] = $value['category_name'];
        }
        $sql = '';
        $sql_list = 'SELECT a.* FROM j_goods_list_edit AS a LEFT JOIN j_goods_sale_edit AS b ON a.main_goods_id=b.main_goods_id WHERE 1=1';
        $sql_count = 'SELECT COUNT(DISTINCT a.main_goods_id) AS id FROM j_goods_list_edit AS a LEFT JOIN j_goods_sale_edit AS b ON a.main_goods_id=b.main_goods_id WHERE 1=1';
        $condition = $where = array();
        $search_goods_name_cn = trim($data['search_goods_name_cn']);
        if(!empty($search_goods_name_cn)){
            $sql .= ' And a.goods_name_cn like "%'.$search_goods_name_cn.'%"';
        }
        if(!empty($data['goods_sku'])){
            $sql .= ' And b.sku like "%'.$data['goods_sku'].'%"';
        }
        if (!empty($data['is_examine'])){
            $sql .= ' And (a.is_examine='.$data['is_examine'].' or b.is_examine='.$data['is_examine'].')';
        }
        $list_count = GoodsListEdit::findBySql($sql_count.$sql,$where)->asArray()->all();
        $count = $list_count[0]['id'];
        $sql .= ' GROUP BY a.main_goods_id';
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'a.id' : 'a.'.$data['columns'][$data['order'][0]['column']]['data'];
        $sql .= ' ORDER BY '.$sort_string.' '.($data['order'][0]['dir'] == 'asc' ? 'asc' : 'desc');
        if ($data['start'] || $data['length']){
            $sql .= ' limit '.$data['start'] .','.$data['length'];
        }
        $list = GoodsListEdit::findBySql($sql_list.$sql,$where)->asArray()->all();
        if(empty($list)){
            $list = array();
        }else{
            $main_goods_id = array_column($list, 'main_goods_id');
            $sale_examine = [];
            if (count($main_goods_id) > 0){
                $sale_edit = GoodsSaleEdit::find()->select('main_goods_id,is_examine')->where(['in','main_goods_id',$main_goods_id])->asArray()->all();
                if (is_array($sale_edit) && count($sale_edit) > 0)foreach ($sale_edit as $saleval){
                    if (!in_array($saleval['main_goods_id'], $sale_examine) && $saleval['is_examine'] == 1){
                        $sale_examine[] = $saleval['main_goods_id'];
                    }
                }
            }
            if (is_array($list) && count($list) > 0)foreach($list as &$val){
                $val['category_step1_name'] = tools::arrayHasValue($goods_category_list,$val['category_step1']) ? $goods_category_list[$val['category_step1']]['category_name'] : '';
                $val['category_step2_name'] = tools::arrayHasValue($goods_category_list,$val['category_step2']) ? $goods_category_list[$val['category_step2']]['category_name'] : '';
                $val['sale_need_examine'] = in_array($val['main_goods_id'], $sale_examine) ? 1 : 2;
            }
        }

        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        //操作日志
        $this->saveLog($this->service,'商品查询','VIEW','获取商品列表' . "\r\n" .  \yii\helpers\Json::encode($list));
        return \yii\helpers\Json::encode($result);
    }

    //添加商品
    public function actionAddMainGoods(){
        $model = new GoodsListEdit();
        $tag_model = new GoodsTagRelation();
        $data = Yii::$app->request->post();
        $seq_where = ['name'=>'seq_main_goods_id'];
        $main_goods = SysSeq::find()->where($seq_where)->asArray()->select('seq_no')->one();
        //mod by lizenan 20180119 【后台需求】关键词维护改进   430  start
        $category_where = ['in','id',[$data['category_step1'],$data['category_step2']]];
        $goods_category = GoodsCategory::find()->select('id,category_name')->where($category_where)->asArray()->all();
        $goods_category = array_combine(array_column($goods_category, 'id'), $goods_category);

        $tag_where = ['id'=>$data['tag_id']];
        $goods_tag = GoodsTag::find()->where($tag_where)->asArray()->one();

        $brand_where = ['id'=>$data['brand_id']];
        $goods_brand = GoodsBrand::find()->where($brand_where)->asArray()->one();
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $data_now['goods_name_cn'] = $data['goods_name_cn'];
            $data_now['goods_name_other'] = $data['goods_name_other'];
            $data_now['category_step1'] = $data['category_step1'];
            $data_now['category_step2'] = $data['category_step2'];
            $data_now['tag_id'] = $data['tag_id'];
            $data_now['tag_name'] = $goods_tag['tag_name'];
            $data_now['brand_id'] = $data['brand_id'];
            $data_now['brand_name'] = $goods_brand['brand_name'];
            $data_now['goods_main_pic'] = $data['goods_main_pic'];
            $data_now['series'] = $data['series'];
            $data_now['goods_pic_title'] = $data['goods_pic_title'];
            $data_now['goods_pic_alt'] = $data['goods_pic_alt'];
            $data_now['unit'] = $data['unit'];
            $data_now['sort'] = !tools::arrayHasValue($data,'sort') || !$data['sort'] ? 1 : $data['sort'];
            $data_now['hidden_price'] = intval($data['hidden_price']);
            //add by lizenan 20180129 【商城需求】商品详情页增加查看同品牌商品的按钮   488  start
            $data_now['see_more_product'] = intval($data['see_more_product']);
            $data_now['brief_cn'] = $data['brief_cn'];
            $data_now['brief_other'] = $data['brief_other'];
            $data_now['use_flg'] = $data['use_flg'];
//             $data_now['identification_id'] = $data['goods_identification'];
            $navigation_identification_id = tools::arrayHasValue($data,'navigation_identification_id') ? explode(',', $data['navigation_identification_id']) : '';
            if ($navigation_identification_id){
                $navigation_identification = NavigationIdentification::find()->select('id,name,is_show')->where(['id'=>$navigation_identification_id])->asArray()->all();
                $hide_nav = [];
                if (is_array($navigation_identification) && count($navigation_identification) > 0)foreach ($navigation_identification as $nav){
                    if ($nav['is_show'] != '1'){
                        $hide_nav[] = $nav['name'];
                    }
                }
                if (count($hide_nav) > 0){
                    throw new \Exception(implode('、', $hide_nav).'导航分类已经在导航分类中不展示，请确认');
                }
                $navigation_identification_name = array_column($navigation_identification, 'name');
            }
            $keyword_list = [
                $data['goods_name_cn'],
                $goods_category[$data['category_step1']]['category_name'],
                $goods_category[$data['category_step2']]['category_name'],
                $goods_tag['tag_name'],
                $goods_brand['brand_name'],
                $data['series'],
                implode(',', $navigation_identification_name)
            ];
            $data_now['keyword_list'] = implode(',', array_filter(array_unique($keyword_list)));
            $keyword = '';
            if(!empty($data['keyword']) && count($data['keyword']) > 0){
                //mod by lizenan 20180129 【后台需求】品牌管理关键词维护修改  start
                $keyword = implode(',', $data['keyword']);
                $data_now['keyword_name'] = array_filter(array_unique(explode(',', $keyword)));
                $data_now['keyword_name'] = implode(',', $data_now['keyword_name']);
            }else{
                $data_now['keyword_name'] = '';
            }
            if (!$data_now['goods_main_pic']){
                throw new \Exception('请上传商品主图');
            }
            if(empty($data['add_main_id'])){
                $editMode = 'ADD';
                $data_now['main_goods_id'] = $main_goods['seq_no'] + 1;
                $data_now['creator'] = $model->getCreator();
                $data_now['create_time'] = date('Y-m-d H:i:s',time());
                $data_now['is_examine'] = 1;
                $res = Yii::$app->db->createCommand()->insert('j_goods_list_edit',$data_now)->execute();
                if(!$res){
                    throw new \Exception('操作失败');
                }

                //更改sys_seq
                $mod_data['seq_no'] = $data_now['main_goods_id'];
                $mod_data['edit_time'] = date('Y-m-d H:i:s',time());
                $ret = SysSeq::updateAll($mod_data, "name=:name",array(':name'=>'seq_main_goods_id'));
                if(!$ret){
                    throw new \Exception('操作失败');
                }

                //商品品类关联
                $red = $tag_model->addGoodsTagRelation($data_now,$goods_tag);
                if(!$red){
                    throw new \Exception('操作失败');
                }
                $data['add_main_id'] = $tag_model->attributes['id'];
                //添加导航分类
                if(count($navigation_identification_id) > 0){
                    $insert_val = [];
                    foreach ($navigation_identification_id as $nav_id){
                        $insert_val[] = [
                            $data_now['main_goods_id'],
                            $nav_id,
                            $model->getCreator(),
                            date('Y-m-d Y:i:s')
                        ];
                    }
                    $fields = ['main_goods_id','navigation_identification_id','creator','create_time'];
                    $add_nav = Yii::$app->db->createCommand()->batchInsert('j_goods_navigation_identification_relation_edit', $fields, $insert_val)->execute();
                    if (!$add_nav){
                        throw new \Exception('操作失败，导航目录添加失败');
                    }
                }
				//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 start
                //新增商品基础信息写日志
                unset($data_now['keyword_list'],$data_now['creator'],$data_now['create_time'],$data_now['is_examine'],$data_now['tag_name'],$data_now['brand_name']);
                $data_now['navigation_identification'] = $navigation_identification_id;
                $model->writeGoodsLog($data_now['main_goods_id'],'',1,$data_now);
				//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 end
            }else{
                $editMode = 'MOD';
                $find_list_edit = GoodsListEdit::find()->where('main_goods_id=:main_goods_id',[':main_goods_id'=>$data['add_main_goods_id']])->asArray()->one();
                $is_examine = $find_list_edit['is_examine'];
                if ($find_list_edit['id']){
                    if ($data['use_flg'] != $find_list_edit['use_flg']){
                        $is_examine = 1;
                    }
                    if ($data['goods_name_cn'] != $find_list_edit['goods_name_cn']){
                        $is_examine = 1;
                    }
                    if ($data['goods_name_other'] != $find_list_edit['goods_name_other']){
                        $is_examine = 1;
                    }
                    if ($data['category_step1'] != $find_list_edit['category_step1']){
                        $is_examine = 1;
                    }
                    if ($data['category_step2'] != $find_list_edit['category_step2']){
                        $is_examine = 1;
                    }
                    if ($data['tag_id'] != $find_list_edit['tag_id']){
                        $is_examine = 1;
                    }
                    if ($data['brand_id'] != $find_list_edit['brand_id']){
                        $is_examine = 1;
                    }
                    if ($data['goods_main_pic'] != $find_list_edit['goods_main_pic']){
                        $is_examine = 1;
                    }
                    if ($data['series'] != $find_list_edit['series']){
                        $is_examine = 1;
                    }
                    if ($data['goods_pic_title'] != $find_list_edit['goods_pic_title']){
                        $is_examine = 1;
                    }
                    if ($data['goods_pic_alt'] != $find_list_edit['goods_pic_alt']){
                        $is_examine = 1;
                    }
                    if ($data_now['keyword_name'] != $find_list_edit['keyword_name']){
                        $is_examine = 1;
                    }
                    if ($data['unit'] != $find_list_edit['unit']){
                        $is_examine = 1;
                    }
                    if ($data['sort'] != $find_list_edit['sort']){
                        $is_examine = 1;
                    }
                    if ($data['hidden_price'] != $find_list_edit['hidden_price']){
                        $is_examine = 1;
                    }
                    if ($data['brief_cn'] != $find_list_edit['brief_cn']){
                        $is_examine = 1;
                    }
                    if ($data['brief_other'] != $find_list_edit['brief_other']){
                        $is_examine = 1;
                    }
//                     if ($data['goods_identification'] != $find_list_edit['identification_id']){
//                         $is_examine = 1;
//                     }
                    if ($data['see_more_product'] != $find_list_edit['see_more_product']){
                        $is_examine = 1;
                    }
                }
                $data_now['is_examine'] = $is_examine;
                //编辑主商品
                $data_now['editor'] = $model->getCreator();
                $data_now['edit_time'] = date('Y-m-d H:i:s',time());
                $ret = $model::updateAll($data_now, "main_goods_id=:main_goods_id",array(':main_goods_id'=>$data['add_main_goods_id']));
                if(!$ret){
                    throw new \Exception('操作失败');
                }
                unset($data_now['is_examine']);
                //编辑sku商品
                $result_where = ['and',['main_goods_id'=>$data['add_main_goods_id']]];
                $result = GoodsSaleEdit::find()->where($result_where)->select('id,main_goods_id')->asArray()->one();
                if(!empty($result)){
                    $ret = GoodsSaleEdit::updateAll($data_now, "main_goods_id=:main_goods_id",array(':main_goods_id'=>$data['add_main_goods_id']));
                    if(!$ret){
                        throw new \Exception('操作失败');
                    }
                }
                $keyword_creat = new GoodsKeyword();
                $keyword = explode(',', $keyword);
                $keyword_list = array_filter(array_unique(array_merge($keyword_list, $keyword)));
                //mod by lizenan 20180129 【后台需求】品牌管理关键词维护修改  end
                $goods_keyword = GoodsKeyword::find()->select('id,name,use_flg')->where(['in','name',$keyword_list])->asArray()->all();
                $goods_keyword = array_combine(array_column($goods_keyword, 'name'), $goods_keyword);
                foreach ($keyword_list as $keyword_list_val){
                    if (tools::arrayHasValue($goods_keyword,$keyword_list_val)){
                        if (intval($goods_keyword[$keyword_list_val]['use_flg']) != 1){
                            $ret = GoodsKeyword::updateAll(['use_flg'=>GoodsKeyword::STATUS_ENABLE], 'id='.$goods_keyword[$keyword_list_val]['id']);
                            if(!$ret){
                                throw new \Exception('操作失败');
                            }
                        }
                        continue;
                    }
                    $fields = ['name','use_flg','sort','creator','create_time'];
                    $keyword_list = [$keyword_list_val,GoodsSaleEdit::USE_FLG_YES,0,$keyword_creat->getCreator(),date('Y-m-d H:i:s')];
                    $add_keyword = Yii::$app->db->createCommand()->batchInsert('j_goods_keyword', $fields, [$keyword_list])->execute();
                    if(!$add_keyword){
                        throw new \Exception('操作失败，关键字添加失败');
                    }
                }
                //mod by lizenan 20180119 【后台需求】关键词维护改进   430  end
				//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 start
                //修改商品基础信息写日志
                if(count($data_now) > 0){
                    unset($data_now['keyword_list'],$data_now['editor'],$data_now['edit_time'],$data_now['tag_name'],$data_now['brand_name']);
                }
                $data_now['navigation_identification'] = array_filter($navigation_identification_id);
                $goods_nav_old = GoodsNavigationIdentificationrelationEdit::find()->select('id,navigation_identification_id')->where('main_goods_id='.$data['add_main_goods_id'])->asArray()->all();
                $find_list_edit['navigation_identification'] = count($goods_nav_old) > 0 ? array_column($goods_nav_old, 'navigation_identification_id') : [];
                if (is_array($data_now['navigation_identification']) && count($data_now['navigation_identification']) > 0)foreach ($data_now['navigation_identification'] as $id){
                    if (!in_array($id, $find_list_edit['navigation_identification'])){
                        $insert_modal = new GoodsNavigationIdentificationrelationEdit();
                        $insert_modal->main_goods_id = $data['add_main_goods_id'];
                        $insert_modal->navigation_identification_id = $id;
                        $insert_modal->creator = $insert_modal->getCreator();
                        $insert_modal->create_time = date('Y-m-d H:i:s');
                        $insert_modal->save();
                        $true = $insert_modal->attributes['id'];
                        if (!$true){
                            throw new \Exception('操作失败，请重试');
                        }
                    }
                }
                if (is_array($goods_nav_old) && count($goods_nav_old) > 0)foreach ($goods_nav_old as $id){
                    if (!in_array($id['navigation_identification_id'], $data_now['navigation_identification'])){
                        $insert_modal = new GoodsNavigationIdentificationrelationEdit();
                        $del = $insert_modal->deleteAll(['id'=>$id['id']]);
                        if(!$del){
                            throw new \Exception('操作失败，二级标识删除失败');
                        }
                    }
                }
                $model->writeGoodsLog($data['add_main_goods_id'],'',2,$data_now,$find_list_edit);
				//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 end
            }
//             if (tools::arrayHasValue($data,'sku')){
//                 $sku = array_unique(array_filter($data['sku']));
//                 if (count($sku) > 0){
//                     $goods_list_where = ['sku'=>$sku];
//                     $goods_list = GoodsSale::find()->where($goods_list_where)->select('sku,main_goods_id,goods_id,goods_name_cn')->asArray()->all();
//                     $goods_list_sku = array_combine(array_column($goods_list, 'sku'), $goods_list);
//                     $model = new GoodsRelation();
//                     $title = $GLOBALS['_GOODS_RELATION_KEY'][4];
//                     $buy_set_id = $title . $data['add_main_id'];
//                     $buy_set_where = ['relation_key'=>$buy_set_id];
//                     $buy_set_list = $model::find()->where($buy_set_where)->asArray()->all();
//                     $set_list = array_combine(array_column($buy_set_list, 'main_goods_id'), $buy_set_list);
//                     foreach($sku_list as $value){
//                         if(empty($goods_list_sku[$value])){
//                             $this->retJson('物料号[ '.$value.' ]不存在,请检查或同步数据之后再提交',500);
//                         }
                        
//                         if(!empty($set_list[$goods_list_sku[$value]['main_goods_id']])){
//                             $this->retJson('物料号[ '.$value.' ]对应的主商品已经添加,请删除之后再提交',500);
//                         }
//                     }
//                 }
//             }
            $transaction->commit();
            //操作日志
            $this->saveLog($this->service,'商品基本资料新增/编辑',$editMode,'名称：' . "\r\n" . $data_now['goods_name_cn']);

            $this->retJson($data_now['goods_name_cn'],200);
        }catch (\Exception $e){
            $transaction->rollBack();
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log('error-> 商品基本资料新增/编辑 失败  ' .  $e->getMessage());
            error_log('error->' . __METHOD__ . ' error:商品基本资料新增/编辑 失败');
            //mod by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }

    //获取主商品详情
    public function actionGetMainGoodsDetail(){
        $data = Yii::$app->request->get();
        $result = $relation_list = $goods_navigation_identification_id = [];
        if (tools::arrayHasValue($data,'id') && !empty($data['id'])){
            $where = ['id'=>$data['id']];
            $result = GoodsListEdit::find()->where($where)->asArray()->one();
            $goods_navigation_identification = GoodsNavigationIdentificationrelationEdit::find()->where('main_goods_id='.$result['main_goods_id'])->asArray()->all();
            $goods_navigation_identification_id = count($goods_navigation_identification) > 0 ? array_column($goods_navigation_identification, 'navigation_identification_id') : [];
//             //商品搭配
//             $relation_where = ['relation_key'=>'goods_'.$data['id']];
//             $relation_list = GoodsRelation::find()->where($relation_where)->asArray()->all();
        }
        //mod by lizenan 20180119 【后台需求】关键词维护改进   430  start
        //关键字
        //$keyword = GoodsKeyword::find()->select('name')->where('use_flg=1')->orderBy('sort asc')->asArray()->all();
        //mod by lizenan 20180119 【后台需求】关键词维护改进   430  end
        //一级分类列表
        $where = ['use_flg'=>1,'parent_id'=>0];
        $category_list = GoodsCategory::find()->where($where)->asArray()->all();
        
        //二级分类列表
        $map = ['and',['use_flg'=>1],['!=','parent_id',0]];
        $category_child_list = GoodsCategory::find()->where($map)->select('id,category_name,parent_id')->asArray()->all();
        $list = array();
        foreach($category_child_list as $value){
            $list[$value['parent_id']][] = $value;
        }
        //品类列表
        $tag_where = ['use_flg'=>1];
        $tag = GoodsCateRelation::find()->where($tag_where)->select('category_id,tag_id,tag_name')->asArray()->all();
        $tag_list = array();
        foreach($tag as $value){
            $tag_list[$value['category_id']][] = $value;
        }
        //品牌列表
        $brand_where = ['use_flg'=>1];
        $brand = GoodsCategoryBrRelation::find()->where($brand_where)->select('category_id,brand_id,brand_name')->asArray()->all();
        $brand_list = array();
        foreach($brand as $value){
            $brand_list[$value['category_id']][] = $value;
        }
        //商品标识
//         $goods_identification = GoodsIdentification::find()->where('type=1 and use_flg=1')->asArray()->all();
        //商品导航标识
        $navigation_identification = NavigationIdentification::find()->orderBy('parent_id asc')->asArray()->all();
        $navigation_identification_list = [];
        $not_show = [];
        if (is_array($navigation_identification) && count($navigation_identification) > 0){
            foreach ($navigation_identification as $val){
                if ($val['parent_id'] == '0'){
                    if ($val['is_show'] == '0'){
                        $not_show[] = $val['id'];
                    }else{
                        $navigation_identification_list[$val['id']] = $val;
                    }
                }else{
                    if (!in_array($val['parent_id'], $not_show) && $val['is_show'] == '1'){
                        $navigation_identification_list[$val['parent_id']]['son'][] = $val;
                    }
                }
            }
            $navigation_identification_list = array_values($navigation_identification_list);
        }
        $model = new UploadForm();
        return $this->render('detail',[/*'keyword'=>$keyword,*/'category_list'=>$category_list,'category_child_list'=>$list,
            'brand_list'=>$brand_list,'tag_list'=>$tag_list,'model'=>$model,'result'=>$result,'relation_list'=>$relation_list,
            'navigation_identification_list'=>$navigation_identification_list,'goods_navigation_identification_id'=>$goods_navigation_identification_id
        ]);
    }
    
    //获取主商品详情
    public function actionGetExamineGoodsDetail(){
        $result = [];
        $data = Yii::$app->request->post();
        $where = ['id'=>$data['id']];
        $new_data = GoodsListEdit::find()->where($where)->asArray()->one();
        if ($new_data['main_goods_id']){
            $old_where = ['main_goods_id' => $new_data['main_goods_id']];
            $goods_nav_edit = GoodsNavigationIdentificationrelationEdit::find()->where($old_where)->asArray()->all();
            $new_data['goods_nav'] = count($goods_nav_edit) > 0 ? array_column($goods_nav_edit, 'navigation_identification_id') : [];
            $old_data = GoodsList::find()->where($old_where)->asArray()->one();
            $goods_nav = GoodsNavigationIdentificationrelation::find()->where($old_where)->asArray()->all();
            $old_data['goods_nav'] = count($goods_nav) > 0 ? array_column($goods_nav, 'navigation_identification_id') : [];
            $result = ['new_data'=>$new_data,'old_data'=>$old_data];
        }
        $this->retJson($result,200);
    }
    
    //获取子商品详情
    public function actionGetExamineGoodsSkuDetail(){
        $result = [];
        $data = Yii::$app->request->post();
        $where = ['id'=>$data['id']];
        $new_data = GoodsSaleEdit::find()->where($where)->asArray()->one();
        if ($new_data['goods_id']){
            $list_edit = GoodsListEdit::find()->where('main_goods_id='.$new_data['main_goods_id'])->asArray()->one();
            if ($list_edit['id'] && intval($list_edit['is_examine']) == 1){
                $this->retJson("请先审核基本资料数据，谢谢",500);
            }
            $old_where = ['goods_id' => $new_data['goods_id']];
            //判断是否是主商品
            $list_edit_id = GoodsListEdit::find()->where($old_where)->asArray()->one();
            if(empty($list_edit_id)){
                $new_data['sale_product'] = 0;
            }else{
                $new_data['sale_product'] = 1;
            }
            $source_edit = GoodsSourceEdit::find()->where($old_where)->asArray()->all();
            if (count($source_edit) > 0){
                $new_data['goods_source'] = $source_edit;
            }
            $old_data = GoodsSale::find()->where($old_where)->asArray()->one();
            if ($old_data['goods_id']){
                $list_id = GoodsList::find()->where($old_where)->asArray()->one();
                if(empty($list_id)){
                    $old_data['sale_product'] = 0;
                }else{
                    $old_data['sale_product'] = 1;
                }
                $source = GoodsSource::find()->where($old_where)->asArray()->all();
                if (count($source) > 0){
                    $old_data['goods_source'] = $source;
                }
            }
            $result = ['new_data'=>$new_data,'old_data'=>$old_data];
        }
        $this->retJson($result,200);
    }

    //同步商品
    public function actionPublishGoods(){
        $data = Yii::$app->request->post();
        $model = new GoodsSaleEdit();
        $list_model = new GoodsListEdit();
        $goods_nav_edit = new GoodsNavigationIdentificationrelationEdit();
        $goods_where = ['and',['id'=>$data['id']],['!=','goods_id',0],['is_examine'=>2]];
        $main_goods_id_list = $list_model::find()->where($goods_where)->asArray()->all();
        $main_goods_id = array_column($main_goods_id_list,'main_goods_id');//需要同步的main_goods_id

        //商品sku集合 goods_sale_edit
        $goods_list_where = ['and',['main_goods_id'=>$main_goods_id],['in','is_examine',[2,3]]];
        $goods = $model::find()->where($goods_list_where)->asArray()->all();
        $goods_list = array();
        foreach($goods as $value){
            if(empty($value['sku'])){
                continue;
            }else{
                $goods_list[$value['main_goods_id']][] = $value;
            }
        }

        //主商品集合 goods_list_edit
        $main_goods_list = array();
        if(!empty($main_goods_id_list)){
            foreach($main_goods_id_list as $value){
                $main_goods_list[$value['main_goods_id']][] = $value;
            }
        }
        foreach($main_goods_id as $value){
            $transaction = Yii::$app->db->beginTransaction();
            try{
                //同步商品表
                if(!empty($goods_list[$value])){
                    $ret = $model->publishGoodsSkuList($goods_list[$value]);
                    if(!$ret){
                        error_log('error-->商品<' . $goods_list[$value][0]['goods_name_cn'] . '同步失败');
                        throw new \Exception('商品<' . $goods_list[$value][0]['goods_name_cn'] . '同步失败');
                    }

                    //改变商品同步状态
                    $data_edit['is_publish'] = 1;
                    $data_edit['editor'] = $model->getCreator();
                    $data_edit['edit_time'] = date('Y-m-d H:i:s',time());
                    $goods_id_where = array_column($goods_list[$value],'goods_id');
                    $goods_list_where = ['goods_id'=>$goods_id_where];
                    $res = $model::updateAll($data_edit,$goods_list_where);
                    if(!$res){
                        error_log('error-->商品<' . $goods_list[$value][0]['goods_name_cn'] . '同步失败');
                        throw new \Exception('商品<' . $goods_list[$value][0]['goods_name_cn'] . '同步失败');
                    }
                }
                //同步主商品表
                if(!empty($main_goods_list[$value])){
                    $ret = $list_model->publishMainList($main_goods_list[$value]);
                    if(!$ret){
                        error_log('error-->商品<' . $goods_list[$value][0]['goods_name_cn'] . '同步失败');
                        throw new \Exception('商品<' . $goods_list[$value][0]['goods_name_cn'] . '同步失败');
                    }
                    //同步商品导航标示表
                    $nav = $goods_nav_edit->publishNav($value);
                    //改变goods_lise_edit的同步状态
                    $list_edit['is_publish'] = 1;
                    $list_edit['editor'] = $model->getCreator();
                    $list_edit['edit_time'] = date('Y-m-d H:i:s',time());
                    $list_where = ['main_goods_id'=>$value];
                    $res = $list_model::updateAll($list_edit,$list_where);
                    if(!$res){
                        error_log('error-->商品<' . $goods_list[$value][0]['goods_name_cn'] . '同步失败');
                        throw new \Exception('商品<' . $goods_list[$value][0]['goods_name_cn'] . '>同步失败');
                    }
					//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 start
                    $goods_id = $main_goods_list[$value][0]['goods_id'];
                    $list_model->writeGoodsLog($value,'',11);
					//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 end
                }

                $transaction->commit();
            }catch (\Exception $e){
                $transaction->rollBack();
                //mod by allen.qiang 20180112 异常处理，日志优化 start
                //error_log('error-> 同步商品 失败  ' .  $e->getMessage());
                error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
                //mod by allen.qiang 20180112 异常处理，日志优化 end

                $this->retJson($e->getMessage(),500);
            }
        }

        //操作日志
        $this->saveLog($this->service,'商品数据同步','SYNC','商品列表：' . "\r\n" . \yii\helpers\Json::encode($main_goods_id));

        $this->retJson('操作成功',200);
    }

    //主商品上架下架
    public function actionChangeMainGoodsStatus(){
        $model = new GoodsListEdit();
        $data = Yii::$app->request->post();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['editor'] = $model->getCreator();
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $main_goods_where = ['id'=>$data['id']];
        $main_goods = $model::find()->where($main_goods_where)->asArray()->one();
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $data_now['is_examine'] = 1;
            if($data['use_flg'] == 0 || $data['use_flg'] == 2){
                //下架售罄所有商品
                if(!empty($main_goods['goods_id'])){
                    $update_where = ['main_goods_id'=>$main_goods['main_goods_id']];
                    $ret = GoodsSaleEdit::updateAll($data_now,$update_where);
                    if(!$ret){
                        throw new \Exception('操作失败');
                    }
                }
                //下架售罄主商品
                $res = GoodsListEdit::updateAll($data_now,$main_goods_where);
                if(!$res){
                    throw new \Exception('操作失败');
                }
            }else{
                //上架主商品
                $ret = $model::updateAll($data_now,$main_goods_where);
                if(!$ret){
                    throw new \Exception('操作失败');
                }
                //上架主商品关联的sku商品
                if(!empty($main_goods['goods_id'])){
                    $update_where = ['goods_id'=>$main_goods['goods_id']];
                    $ret = GoodsSaleEdit::updateAll($data_now,$update_where);
                    if(!$ret){
                        throw new \Exception('操作失败');
                    }
                }
            }
            $transaction->commit();
            $this->retJson('操作成功',200);
        }catch (\Exception $e){
            $transaction->rollBack();
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log('error-> 主商品上架下架 失败  ' .  $e->getMessage());
            error_log('error->' . __METHOD__ . ' error:主商品上架下架 失败 ' . $e->getMessage());
            //mod by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }

    //获取商品已选的规格
    public function actionGetGoodsSku(){
        $data = Yii::$app->request->post();
        $data_where = ['id'=>$data['id']];
        $main_goods_list = GoodsListEdit::find()->where($data_where)->select('main_goods_id')->asArray()->one();
        $result_where = ['main_goods_id'=>$main_goods_list['main_goods_id'],'use_flg'=>1];
        $result = GoodsSpecRelation::find()->where($result_where)->asArray()->all();
        if(!empty($result)){
            $is_checked_spec = array_column($result,'spec_id');
            $checked['is_checked_spec'] = $is_checked_spec;
            $checked['remark'] = array_combine(array_column($result,'spec_id'), $result);
            $old_color_spec_id_list = $old_size_spec_id_list = $old_other_spec_id_list = array();
            foreach($result as $value){
                if($value['spec_type'] == 1){
                    $old_color_spec_id_list[] = $value['spec_id'];
                }elseif($value['spec_type'] == 2){
                    $old_size_spec_id_list[] = $value['spec_id'];
                }else{
                    $old_other_spec_id_list[] = $value['spec_id'];
                }
            }
            $old_color_spec_id = count($old_color_spec_id_list) > 0 ? implode(',',$old_color_spec_id_list) : '';
            $old_size_spec_id = count($old_size_spec_id_list) > 0 ? implode(',',$old_size_spec_id_list) : '';
            $old_other_spec_id = count($old_other_spec_id_list) > 0 ? implode(',',$old_other_spec_id_list) : '';
            $checked['old_color_spec_id'] = $old_color_spec_id;
            $checked['old_size_spec_id'] = $old_size_spec_id;
            $checked['old_other_spec_id'] = $old_other_spec_id;
        }else{
            $checked = array();
        }
        $this->retJson($checked,200);
    }

    //添加商品规格
    public function actionAddSku(){
        $goods_spec_model = new GoodsSpecRelation();
        $data = Yii::$app->request->post();
        if(empty($data['add_main_id'])){
            error_log(print_r($data,1));
            $this->retJson('数据错误，请联系管理员',500);
        }
        $where = ['id'=>$data['add_main_id']];
        $goods_one = GoodsListEdit::find()->where($where)->asArray()->one();
        //获取规格值
        $goods_spec = GoodsSpec::find()->select('id,spec_name,spec_val,spec_group_id')->asArray()->all();
        $goods_spec_list = array_combine(array_column($goods_spec, 'id'), $goods_spec);
        //颜色、尺寸必选
        if(!tools::arrayHasValue($data,'color_spec_id') || !tools::arrayHasValue($data,'size_spec_id') || 
            count($data['color_spec_id']) == 0 || count($data['size_spec_id']) == 0){
            $this->retJson('至少选择一种尺寸或颜色',500);
        }
        $color_spec_id = $data['color_spec_id'];
        $size_spec_id = $data['size_spec_id'];
        $other_spec_id = tools::arrayHasValue($data,'other_spec_id') ? $data['other_spec_id'] : [];
        $color_spec_title = tools::arrayHasValue($data,'color_spec_title') ? $data['color_spec_title'] : [];
        $color_spec_pic = tools::arrayHasValue($data,'spec_color_pic') ? $data['spec_color_pic'] : [];
        $transaction = Yii::$app->db->beginTransaction();
        try{
            //新规格id数组
            $goods_sku_list = array_merge($color_spec_id,$size_spec_id,$other_spec_id);
            //新规格remark数组
            $goods_sku_remark = array_combine($color_spec_id, $color_spec_title);
            //新规格pic数组
            $goods_sku_pic = array_combine($color_spec_id, $color_spec_pic);
            $spec_relation = GoodsSpecRelation::find()->select('id,spec_id,spec_name,remark,color_pic')->where(['main_goods_id'=>$goods_one['main_goods_id']])->asArray()->all();
            if (is_array($spec_relation) && count($spec_relation) > 0)foreach ($spec_relation as $spec_relation_val){
                if (in_array($spec_relation_val['spec_id'], $color_spec_id)
                    && ($spec_relation_val['remark'] != $goods_sku_remark[$spec_relation_val['spec_id']] || $spec_relation_val['color_pic'] != $goods_sku_pic[$spec_relation_val['spec_id']])){
                        GoodsSpecRelation::updateAll(['remark'=>$goods_sku_remark[$spec_relation_val['spec_id']],'color_pic'=>$goods_sku_pic[$spec_relation_val['spec_id']]],['id'=>$spec_relation_val['id']]);
                }
            }
            //旧规格id数组f
            $spec_id = count($spec_relation) > 0 ? array_column($spec_relation, 'spec_id') : [];
            //新规格id数组和旧规格id数组比较获取差集
            $goods_sku_list = array_diff($goods_sku_list,$spec_id);
            //添加商品规格对应
            if (count($goods_sku_list) > 0){
                $add_result = $goods_spec_model->addGoodsSpecRelation($goods_one['main_goods_id'],$goods_sku_list,$goods_spec_list,$goods_sku_remark,$goods_sku_pic);
                if(empty($add_result)){
                    throw new \Exception('规格添加失败');
                }
            }

//             //根据规格类型划分规格组
//             $normal_spec_id_list = array();
//             $color_spec_id_list = array();
//             foreach($add_result as $value){
//                 if($value['spec_type'] == 0){ //非COLOR
//                     $normal_spec_id_list[] = $value['spec_id'];
//                 }
//                 if($value['spec_type'] == 1){ //COLOR
//                     $color_spec_id_list[] = $value['spec_id'];
//                 }
//             }

//             //获取goods_id
//             $seq_where = ['name'=>'seq_goods_id'];
//             $goods_id = SysSeq::find()->where($seq_where)->asArray()->select('seq_no')->one();
//             $goods_id_start = $goods_id['seq_no'];//开始

//             //规格与规格组合
//             $sku_list_id = array();

//             if(empty($color_spec_id_list)){
//                 //没有颜色规格
//                 foreach($normal_spec_id_list as $value){
//                     $goods_sku_where = ['and',['main_goods_id'=>$goods_one['main_goods_id']],['!=','goods_id',0],['spec'=>$value],['use_flg'=>1]];
//                     $res = $model::find()->where($goods_sku_where)->select('id')->asArray()->one();
//                     if($res){
//                         continue;
//                     }else{
//                         $goods_id_start ++;
//                         $sku_list_id[] = array('spec_normal_id'=>$value,'spec_color_id'=>0,'goods_id'=>$goods_id_start);
//                     }
//                 }
//             }else{
//                 foreach($normal_spec_id_list as $value){
//                     foreach($color_spec_id_list as $color){
//                         $goods_sku_where = ['and',['main_goods_id'=>$goods_one['main_goods_id']],['!=','goods_id',0],['spec'=>$value],['spec_color'=>$color],['use_flg'=>1]];
//                         $res = $model::find()->where($goods_sku_where)->select('id')->asArray()->one();
//                         if($res){
//                             continue;
//                         }else{
//                             $goods_id_start ++;
//                             $sku_list_id[] = array('spec_normal_id'=>$value,'spec_color_id'=>$color,'goods_id'=>$goods_id_start);
//                         }
//                     }
//                 }
//             }
//             $goods_id_end = $goods_id_start;//结束

//             //修改sys_seq
//             $mod_data['seq_no'] = $goods_id_end;
//             $mod_data['edit_time'] = date('Y-m-d H:i:s',time());
//             $ret = SysSeq::updateAll($mod_data, "name=:name",array(':name'=>'seq_goods_id'));
//             if(!$ret){
//                 throw new \Exception('操作失败');
//             }

//             //添加商品
//             $list = array();
//             foreach($sku_list_id as $key=>$value){
//                 $list[] = [$goods_one['main_goods_id'],$value['goods_id'],$goods_one['goods_name_cn'],$goods_one['goods_name_other'],
//                     $goods_one['category_step1'],$goods_one['category_step2'],$value['spec_normal_id'],$goods_spec_list[$value['spec_normal_id']]['spec_val'],
//                     $value['spec_color_id'],empty($value['spec_color_id']) ? '' : $goods_spec_list[$value['spec_color_id']]['spec_val'],$goods_one['tag_id'],$goods_one['tag_name'],
//                     $goods_one['unit'],$goods_one['brief_cn'],$goods_one['brief_other'],$goods_one['description'],$goods_one['brand_id'],$goods_one['brand_name'],
//                     $goods_one['goods_main_pic'],$goods_one['goods_pic_title'],$goods_one['goods_pic_alt'],$model->getCreator(),date('Y-m-d H:i:s',time())];
//             }
//             $fields = ['main_goods_id','goods_id','goods_name_cn','goods_name_other','category_step1','category_step2',
//                 'spec','spec_val','spec_color','spec_color_val','tag_id','tag_name','unit','brief_cn','brief_other',
//                 'description','brand_id','brand_name','goods_main_pic','goods_pic_title','goods_pic_alt','creator','create_time'];
//             $res = Yii::$app->db->createCommand()->batchInsert('j_goods_sale_edit', $fields, $list)->execute();
//             if(!$res){
//                 throw new \Exception('操作失败');
//             }
			//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 start
            //修改商品规格写日志
            $new_spec_relation = GoodsSpecRelation::find()->select('id,spec_id,spec_name,remark,color_pic')->where(['main_goods_id'=>$goods_one['main_goods_id']])->asArray()->all();
            $model = new GoodsListEdit();
            $model->writeGoodsLog($goods_one['main_goods_id'],'',3,$new_spec_relation,$spec_relation);
			//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 end
            $transaction->commit();
            //操作日志
            $this->saveLog($this->service,'商品添加规格','ADD','商品：' . $data['add_main_id'] .' 规则列表：' . "\r\n" . \yii\helpers\Json::encode($goods_sku_list));

            $this->retJson($data['add_main_id'],200);
        }catch (\Exception $e){
            $transaction->rollBack();

            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log('error-> 添加商品规格 失败  ' .  $e->getMessage());
            error_log('error->' . __METHOD__ . ' error:添加商品规格 失败 ' . $e->getMessage());
            //mod by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }

    //获取商品规格列表
    public function actionGetSkuList(){
        $model = new GoodsSaleEdit();
        $data = Yii::$app->request->post();
        $count = 0;
        $list = array();
        if(!empty($data['select_goods_id'])){
            //获取主商品信息
            $where = ['id'=>$data['select_goods_id']];
            $main_goods_list = GoodsListEdit::find()->where($where)->select('id,main_goods_id')->asArray()->one();
            $condition = ['main_goods_id'=>$main_goods_list['main_goods_id']];
            $sale_count = GoodsSaleEdit::find()->where($condition)->count();
            if (intval($sale_count) == 0){
                $where_sql = 'main_goods_id='.$main_goods_list['main_goods_id'].' and use_flg=1';
                $goods_spec = GoodsSpecRelation::find()->select('spec_id,spec_group_id,spec_val,spec_type')->where($where_sql)->asArray()->all();
                $spec_group_id = array_unique(array_column($goods_spec, 'spec_group_id'));
                $goods_spec = array_combine(array_column($goods_spec, 'spec_id'), $goods_spec);
                $goods_spec_arr = $goods_spec_array = $goods_spec_com = [];
                if (is_array($goods_spec) && count($goods_spec) > 0)foreach ($goods_spec as $goods_spec_val){
                    $goods_spec_array[$goods_spec_val['spec_type']][] = $goods_spec_val;
                    $goods_spec_arr[$goods_spec_val['spec_type']][] = $goods_spec_val['spec_id'];
                }
                $goods_spec_com = array_merge($goods_spec_arr);
                $result_2 = tools::arrayHasValue($goods_spec_com,0) ? $goods_spec_com[0] : [];
                for($i=1;$i<count($goods_spec_com);$i++){
                    $size= count($result_2);
                    for($j=0;$j<$size;$j++){
                        //遍历要进行组合的数组
                        for($k=0;$k<count($goods_spec_com[$i]);$k++){
                            //把组合的字符串放入到结果数组最后一个成员中
                            //这里使用下标0是因为当这个下标0组合完毕之后就没有用了，在下面我们要移除掉这个成员
                            $result_2[] = [$result_2[0],$goods_spec_com[$i][$k]];
                        }
                        //当第一个成员组合完毕，删除这第一个成员
                        array_shift($result_2);
                    }
                }
                if (is_array($result_2) && count($result_2) > 0)foreach ($result_2 as $val){
                    $spec_val = $spec_color_val = '';
                    if (is_array($val) && count($val) > 0)foreach ($val as $val_son){
                        if ($goods_spec[$val_son]['spec_type'] == '1'){
                            $spec_color_val = $goods_spec[$val_son]['spec_id'];
                        }else{
                            $spec_val = $goods_spec[$val_son]['spec_id'];
                        }
                    }
                    $list[] = [
                        'id'=>'',
                        'goods_name_cn'=>'',
                        'goods_id'=>'',
                        'sku'=>'',
                        'spec_val'=>$spec_val,
                        'spec_color_val'=>$spec_color_val,
                        'sort'=>'--',
                        'use_flg'=>'',
                        'is_examine'=>'',
                        'goods_spec'=>$goods_spec_array
                    ];
                }
            }else{
                if(!empty($data['search_goods_sku'])){
                    $condition = ['and',['main_goods_id'=>$main_goods_list['main_goods_id']],['like','sku',$data['search_goods_sku']]];
                }
                $query = $model::find()->where($condition);
                $count = $query->count();
                $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
                $list = $query->offset($data['start'])->limit($data['length'])
                    ->orderBy(array("$sort_string"=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->asArray()->all();
                if(empty($list)){
                    $list = array();
                }
            }
        }
        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    //商品上架下架
    public function actionChangeGoodsStatus(){
        $model = new GoodsSaleEdit();
        $list_model = new GoodsListEdit();
        $data = Yii::$app->request->post();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['editor'] = $model->getCreator();
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $main_goods_where = ['id'=>$data['id']];
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $main_goods = $model::find()->where($main_goods_where)->asArray()->one();
            $list_edit = $list_model->find()->where('main_goods_id='.$main_goods['main_goods_id'])->asArray()->one();
            $goods_list = $model::find()->where('main_goods_id='.$main_goods['main_goods_id'].' and use_flg='.$model::STATUS_ENABLE)->count();
            if ($list_edit['goods_id'] == $main_goods['goods_id'] && $data_now['use_flg'] == '0' && $goods_list > 1){
                throw new \Exception('您下架的商品为主商品，不能下架<br/>其他商品设置为主商品后，此商品可下架');
            }
            if ($list_edit['use_flg'] != '1'){
                throw new \Exception('基础信息状态为下架/售罄<br/>请上架基础信息之后再修改子商品状态');
            }
            $data_now['is_examine'] = 1;
            $ret = $model::updateAll($data_now,$main_goods_where);
            if(!$ret){
                throw new \Exception('操作失败');
            }
            $main_goods_where = ['main_goods_id'=>$main_goods['main_goods_id']];
            $goods_list = $model::find()->where($main_goods_where)->asArray()->all();
            $ret = $list_model->changeUseFlg($goods_list,$data['use_flg'],$main_goods['main_goods_id']);
            if(!$ret){
                throw new \Exception('操作失败');
            }
			//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 start
            //修改子商品上下架
            $list_model->writeGoodsLog($main_goods['main_goods_id'],$main_goods['goods_id'],6,['use_flg'=>$data['use_flg']],['use_flg'=>$main_goods['use_flg']]);
            //add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 end
            $transaction->commit();
            $this->retJson('操作成功',200);
        }catch (\Exception $e){
            $transaction->rollBack();
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log('error-> 商品上架下架 失败  ' .  $e->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }

    /**
     * 获取商品详情
     */
    public function actionGetGoodsDetail(){
        $data = Yii::$app->request->post();
        if (!$data['id'] && !$data['goods_list_id']){
            $this->retJson('操作失败，请联系管理员',500);
        }
        if ($data['id']){
            $where = ['id'=>$data['id']];
            $result = GoodsSaleEdit::find()->where($where)->asArray()->one();
            //获取商品素材
            $source_where = ['goods_id'=>$result['goods_id']];
            $source = GoodsSourceEdit::find()->where($source_where)->asArray()->all();
            if(empty($source)){
                $source = array();
            }
            $result['source_list'] = $source;
            //判断是否是主商品
            $list_id_where = ['goods_id'=>$result['goods_id']];
            $list_id = GoodsListEdit::find()->where($list_id_where)->asArray()->one();
            if(empty($list_id)){
                $result['is_main'] = 0;
            }else{
                $result['is_main'] = 1;
            }
        }else{
            $where = ['id'=>$data['goods_list_id']];
            $result = GoodsListEdit::find()->select('id,sku,main_goods_id,goods_name_cn,hidden_price')->where($where)->asArray()->one();
            $has_where = [
                'spec'=>$data['spec_val'],
                'spec_color'=>$data['spec_color_val'],
                'main_goods_id'=>$result['main_goods_id']
            ];
            $has_sale = GoodsSaleEdit::find()->where($has_where)->asArray()->all();
            if (count($has_sale) > 0){
                $this->retJson('规格和颜色组合的商品已存在',500);
            }
            if($result['sku']){
                $result['is_main'] = 0;
            }else{
                $result['is_main'] = 1;
            }
        }
        $this->retJson($result,200);
    }

    //编辑商品详情
    public function actionUpdateGoodsSku(){
        $model = new GoodsSaleEdit();
        $goods_list_edit = new GoodsListEdit();
        $data = Yii::$app->request->post();
        if(empty($data['source_url'])){
            $this->retJson('请上传商品图片或视频',500);
        }
//         $file_url = $data['source_url'];
//         foreach($file_url as $value){
//             if(empty($value)){
//                 $this->retJson('请删除空数据之后在提交',500);
//             }
//         }
        $transaction = Yii::$app->db->beginTransaction();
        try{
            //编辑goods_sale_edit
            $data_now['sku'] = $data['sku'];
            $data_now['forsale'] = $data['forsale'];
            //mod by lizenan 20180119 【后台需求】将原本SKU的系列号转移至商品基础资料维护中   469  start
            //$data_now['series'] = $data['series'];
            $data_now['model'] = $data['model'];
            $data_now['market_price'] = $data['market_price'];
            $data_now['sale_price'] = $data['sale_price'];
            $data_now['use_flg'] = $data['use_flg'];

            //检验物料号是否已存在
            $check_sku = ['sku'=>$data_now['sku']];
            $check_list = $model::find()->where($check_sku)->select('id')->asArray()->one();
            if(!empty($check_list) && $check_list['id'] != $data['update_goods_id']){
                throw new \Exception('物料号已存在');
            }
            $goods_list_id = $data['goods_list_id'];
            $list_edit = GoodsListEdit::findOne($goods_list_id);
            $main_use_flg = $list_edit->use_flg;
            if (intval($data_now['use_flg']) == 0 && $main_use_flg != intval($data_now['use_flg'])){
                throw new \Exception('您下架的商品为主商品，不能下架<br/>其他商品设置为主商品后，此商品可下架');
            }
            $marking_img_id = $data['marking_img_id'];
            $marking_img_arr = [];
            if ($marking_img_id){
                $marking_img_arr = explode('||', $marking_img_id);
                if (intval($marking_img_arr[0]) > 0){
                    $find_marking_img = GoodsMarkingImg::find()->where('id=:id',[':id'=>$marking_img_id])->count();
                    if (!$find_marking_img){
                        throw new \Exception('商品打标图片不存在');
                    }
                }
                $data_now['marking_img_id'] = intval($marking_img_arr[0]) > 0 ? $marking_img_arr[0] : '';
            }
            $add = false;
            if (!$data['update_goods_id']){
                $editMode = 'ADD';
                $seq_where = ['name'=>'seq_goods_id'];
                $goods_id = SysSeq::find()->where($seq_where)->asArray()->select('seq_no')->one();
                $goods_id_start = $goods_id['seq_no'];//开始
                $mod_data['seq_no'] = intval($goods_id_start)+1;
                $mod_data['edit_time'] = date('Y-m-d H:i:s',time());
                $spec_ids = [$data['spec_val'],$data['spec_color_val']];
                $goods_spec = GoodsSpec::find()->select('id,spec_val')->where(['in','id',$spec_ids])->asArray()->all();
                $goods_spec = array_combine(array_column($goods_spec, 'id'), $goods_spec);
                $data_now['main_goods_id'] = $list_edit->main_goods_id;
                $data_now['goods_id'] = $mod_data['seq_no'];
                $data_now['goods_name_cn'] = $list_edit->goods_name_cn;
                $data_now['goods_name_other'] = $list_edit->goods_name_other;
                $data_now['category_step1'] = $list_edit->category_step1;
                $data_now['category_step2'] = $list_edit->category_step2;
                $data_now['spec'] = $data['spec_val'];
                $data_now['spec_val'] = $goods_spec[$data['spec_val']]['spec_val'];
                $data_now['spec_color'] = $data['spec_color_val'];
                $data_now['spec_color_val'] = $goods_spec[$data['spec_color_val']]['spec_val'];
                $data_now['tag_id'] = $list_edit->tag_id;
                $data_now['tag_name'] = $list_edit->tag_name;
                $data_now['unit'] = $list_edit->unit;
                $data_now['brief_cn'] = $list_edit->brief_cn;
                $data_now['brief_other'] = $list_edit->brief_other;
                $data_now['description'] = $list_edit->description;
                $data_now['brand_id'] = $list_edit->brand_id;
                $data_now['brand_name'] = $list_edit->brand_name;
                $data_now['goods_main_pic'] = $list_edit->goods_main_pic;
                $data_now['goods_pic_title'] = $list_edit->goods_pic_title;
                $data_now['goods_pic_alt'] = $list_edit->goods_pic_alt;
                $data_now['creator'] = $model->getCreator();
                $data_now['create_time'] = date('Y-m-d H:i:s',time());
//                 $fields = ['sku','forsale','series','model','market_price','sale_price','use_flg','main_goods_id','goods_id',
//                     'goods_name_cn','goods_name_other','category_step1','category_step2','spec','spec_val','spec_color',
//                     'spec_color_val','tag_id','tag_name','unit','brief_cn','brief_other','description','brand_id',
//                     'brand_name','goods_main_pic','goods_pic_title','goods_pic_alt','creator','create_time'];
                $fields = ['sku','forsale','model','market_price','sale_price','use_flg','marking_img_id','main_goods_id','goods_id',
                    'goods_name_cn','goods_name_other','category_step1','category_step2','spec','spec_val','spec_color',
                    'spec_color_val','tag_id','tag_name','unit','brief_cn','brief_other','description','brand_id',
                    'brand_name','goods_main_pic','goods_pic_title','goods_pic_alt','creator','create_time'];
                $add_sale = Yii::$app->db->createCommand()->batchInsert('j_goods_sale_edit', $fields, [$data_now])->execute();
                if(!$add_sale){
                    throw new \Exception('操作失败，子商品添加失败');
                }
                $ret = SysSeq::updateAll($mod_data, "name=:name",array(':name'=>'seq_goods_id'));
                if(!$ret){
                    throw new \Exception('操作失败，请联系系统管理员');
                }
                //获取商品详情
                $goods_detail_where = ['goods_id'=>$mod_data['seq_no']];
                $add = true;
				//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 start
                //新增子商品写日志
                unset(
                    $data_now['goods_name_other'],
                    $data_now['category_step1'],
                    $data_now['category_step2'],
                    $data_now['spec'],
                    $data_now['spec_val'],
                    $data_now['spec_color'],
                    $data_now['spec_color_val'],
                    $data_now['tag_id'],
                    $data_now['tag_name'],
                    $data_now['unit'],
                    $data_now['brief_cn'],
                    $data_now['brief_other'],
                    $data_now['description'],
                    $data_now['brand_id'],
                    $data_now['brand_name'],
                    $data_now['goods_main_pic'],
                    $data_now['goods_pic_title'],
                    $data_now['goods_pic_alt'],
                    $data_now['creator'],
                    $data_now['create_time']
                );
                $data_now['is_main'] = $data['is_main'];
                $data_now['source_url'] = $data['source_url'];
                $goods_list_edit->writeGoodsLog($data_now['main_goods_id'],$mod_data['seq_no'],4,$data_now);
				//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 end
            }else{
                $editMode = 'MOD';
                $data_now['editor'] = $model->getCreator();
                $data_now['edit_time'] = date('Y-m-d H:i:s',time());
                $sale_edit = $model::find()->where('id='.$data['update_goods_id'])->asArray()->one();
                if ($list_edit->goods_id == intval($sale_edit['goods_id']) && $data['is_main'] == '1'){
                    $sale_edit_list = $model::find()->where('main_goods_id='.$list_edit->main_goods_id.' and use_flg='.$model::STATUS_ENABLE)->asArray()->all();
                    if($data['use_flg'] != '1' && count($sale_edit_list) > 1){
                        throw new \Exception('您下架的商品为主商品，不能下架<br/>其他商品设置为主商品后，此商品可下架');
                    }
                }
                $source_edit = GoodsSourceEdit::find()->where('goods_id='.$sale_edit['goods_id'])->asArray()->all();
                $is_examine = $sale_edit['is_examine'];
                if ($list_edit->goods_id == intval($sale_edit['goods_id']) && $data['is_main'] == '0'){
                    $is_examine = 1;
                }
                if ($list_edit->goods_id != intval($sale_edit['goods_id']) && $data['is_main'] == '1'){
                    $is_examine = 1;
                }
                if ($data['goods_name_cn'] != $sale_edit['goods_name_cn']){
                    $is_examine = 1;
                }
                if ($data['sku'] != $sale_edit['sku']){
                    $is_examine = 1;
                }
                if (count($source_edit) != count(array_filter($data['source_url']))){
                    $is_examine = 1;
                }elseif (count($data['source_url']) > 0){
                    for ($i=0;$i<count($source_edit);$i++){
                        if ($source_edit[$i]['source_url'] != $data['source_url'][$i]){
                            $is_examine = 1;
                        }
                    }
                }
                if ($data['forsale'] != $sale_edit['forsale']){
                    $is_examine = 1;
                }
                if ($data['model'] != $sale_edit['model']){
                    $is_examine = 1;
                }
                if (tools::arrayHasValue($marking_img_arr,0) && $marking_img_arr[0] != $sale_edit['marking_img_id']){
                    $is_examine = 1;
                }
                if ($data['market_price'] != $sale_edit['market_price']){
                    $is_examine = 1;
                }
                if ($data['sale_price'] != $sale_edit['sale_price']){
                    $is_examine = 1;
                }
                if ($data['use_flg'] != $sale_edit['use_flg']){
                    $is_examine = 1;
                }
                $data_now['is_examine'] = $is_examine;
                //更新商品信息
                $ret = $model::updateAll($data_now, "id=:id",array(':id'=>$data['update_goods_id']));
                if(!$ret){
                    throw new \Exception('操作失败');
                }
                //获取商品详情
                $goods_detail_where = ['id'=>$data['update_goods_id']];
				//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 start
                //修改子商品写日志
                unset($data_now['editor'],$data_now['edit_time'],$data_now['is_examine']);
                if ($data['is_main'] == '1'){
                    if ($list_edit->goods_id != intval($sale_edit['goods_id'])){
                        $data_now['is_main'] = 1;
                        $sale_edit['is_main'] = 2;
                    }else{
                        $data_now['is_main'] = $sale_edit['is_main'] = 1;
                    }
                }else{
                    if ($list_edit->goods_id == intval($sale_edit['goods_id'])){
                        $data_now['is_main'] = 2;
                        $sale_edit['is_main'] = 1;
                    }else{
                        $data_now['is_main'] = $sale_edit['is_main'] = 2;
                    }
                }
                //修改子商品写日志
                $data_now['source_url'] = $data['source_url'];
                $goods_list_edit->writeGoodsLog($list_edit->main_goods_id,$sale_edit['goods_id'],5,$data_now,$sale_edit);
				//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 end
            }
            //mod by lizenan 20180119 【后台需求】将原本SKU的系列号转移至商品基础资料维护中   469  start
            $goods_detail = $model::find()->where($goods_detail_where)->asArray()->one();
            $edit_model = new GoodsListEdit();
            //编辑主商品  操作goods_list_edit
            if(intval($data['is_main']) == 1){
                $re_del = $edit_model->UpdateMainGoods($goods_detail);
                if(!$re_del){
                    throw new \Exception('操作失败');
                }
            }else{
                //主商品是否存在goods_id
                $main_where = ['main_goods_id'=>$goods_detail['main_goods_id']];
                $main_detail = $edit_model::find()->where($main_where)->select('id,goods_id')->asArray()->one();
                if(empty($main_detail['goods_id'])){
                    $re_del = $edit_model->UpdateMainGoods($goods_detail);
                    if(!$re_del){
                        throw new \Exception('操作失败');
                    }
                }
            }
            //下架
            if(intval($data_now['use_flg']) == 0){
                $use_flg_where = ['main_goods_id'=>$goods_detail['main_goods_id']];
                $goods_sku_list = $model::find()->where($use_flg_where)->select('id,use_flg')->asArray()->all();
                $ret = $edit_model->changeUseFlg($goods_sku_list,$data_now['use_flg'],$goods_detail['main_goods_id']);
                if(!$ret){
                    throw new \Exception('操作失败');
                }
            }
            //添加商品资源  操作goods_source
            $source_model = new GoodsSourceEdit();
            if(!empty($data['source_url'])){
                $source_where = ['goods_id'=>$goods_detail['goods_id']];
                $check_source = $source_model::find()->where($source_where)->select('id')->asArray()->one();
                if(!empty($check_source)){
                    $re_del = $source_model::deleteAll($source_where);
                    if(!$re_del){
                        throw new \Exception('操作失败');
                    }
                }
                $re_source = $source_model->addSource($data['source_url'],$data['source_sort'],$data['source_type'],$goods_detail);
                if(!$re_source){
                    throw new \Exception('操作失败');
                }
            }
            $transaction->commit();
            $goods_detail['is_add'] = $add;
            //操作日志
            $this->saveLog($this->service,'SKU商品编辑', $editMode ,'SKU：' .$data_now['sku'] );

            $this->retJson($goods_detail,200);
        }catch (\Exception $e){
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log('error-> 编辑商品详情失败  ' .  $e->getMessage());
            error_log('error->' . __METHOD__ . ' error:编辑商品详情失败 ' . $e->getMessage());
            //mod by allen.qiang 20180112 异常处理，日志优化 end
            $transaction->rollBack();
            $this->retJson($e->getMessage(),500);
        }
    }

    /**
     * 审核商品基本资料
     */
    public function actionExamineGoods(){
        $goods_list_edit = new GoodsListEdit();
        $goods_list = new GoodsList();
        $data = Yii::$app->request->post();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $is_examine = $data['status'];
            $id = $data['id'];
            $oper = $goods_list->getCreator();
            $operTime = date('Y-m-d H:i:s');
            $change = [];
            switch ($is_examine){
                case '3':
                    $list_edit = $goods_list_edit::find()->where('id=:id',[':id'=>$id])->asArray()->one();
                    if ($list_edit['main_goods_id']){
                        $list = $goods_list::find()->where('main_goods_id='.$list_edit['main_goods_id'])->asArray()->one();
                        if($list['id']){
                            if ($list['sku'] != $list_edit['sku']){
                                $sale_edit = GoodsSaleEdit::find()->where('sku='.$list['sku'])->asArray()->one();
                                if (!$sale_edit){
                                    $sale = GoodsSale::find()->where('sku='.$list['sku'])->asArray()->one();
                                    unset($sale['id']);
                                    unset($sale['creator']);
                                    unset($sale['create_time']);
                                    $sale['is_examine'] = $is_examine;
                                    $sale['editor'] = $oper;
                                    $sale['edit_time'] = $operTime;
                                    $sale_res = GoodsSaleEdit::updateAll($sale,['goods_id'=>$sale['goods_id']]);
                                    if (!$sale_res){
                                        throw new \Exception('审核状态修改失败');
                                    }
                                }
                            }
                            unset($list['id']);
                            unset($list['creator']);
                            unset($list['create_time']);
                            $change = $list;
                        }
                    }
                case '2':
                    $change['is_examine'] = $is_examine;
                    $change['editor'] = $oper;
                    $change['edit_time'] = $operTime;
                    break;
            }
            $res = $goods_list_edit::updateAll($change,['id'=>$id]);
            if (!$res){
                throw new \Exception('审核状态修改失败');
            }
			//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 start
            //审核商品基础信息写日志
            $list_edit = $goods_list_edit::find()->select(
                'main_goods_id,goods_id,goods_name_cn,goods_name_other,category_step1,category_step2,tag_id,brand_id,series,goods_main_pic,goods_pic_title,goods_pic_alt,keyword_name,unit,sort,hidden_price,see_more_product,use_flg,brief_cn,brief_other'
            )->where('id=:id',[':id'=>$id])->asArray()->one();
            $list = GoodsList::find()->select(
                'goods_name_cn,goods_name_other,category_step1,category_step2,tag_id,brand_id,series,goods_main_pic,goods_pic_title,goods_pic_alt,keyword_name,unit,sort,hidden_price,see_more_product,use_flg,brief_cn,brief_other'
            )->where('main_goods_id=:main_goods_id',[':main_goods_id'=>$list_edit['main_goods_id']])->asArray()->one();
            $goods_nav_edit = GoodsNavigationIdentificationrelationEdit::find()->where(['main_goods_id'=>$list_edit['main_goods_id']])->asArray()->all();
            $list_edit['navigation_identification'] = count($goods_nav_edit) > 0 ? array_column($goods_nav_edit, 'navigation_identification_id') : [];
            $goods_nav = GoodsNavigationIdentificationrelation::find()->where(['main_goods_id'=>$list_edit['main_goods_id']])->asArray()->all();
            $list['navigation_identification'] = count($goods_nav) > 0 ? array_column($goods_nav, 'navigation_identification_id') : [];
            $goods_list_edit->writeGoodsLog($list_edit['main_goods_id'],$list_edit['goods_id'],7,$list_edit,$list,$is_examine);
			//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 end
            $transaction->commit();
            //操作日志
            $this->saveLog($this->service,'商品基本资料审核', 'EXAMINE' ,'goods_list_edit id = ' . $id . "\r\n" .  \yii\helpers\Json::encode($change));

            $this->retJson("操作成功",200);
        } catch (\Exception $e) {
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:商品基本资料审核失败 ' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
            $transaction->rollBack();
        }
    }

    /**
     * 审核商品子sku信息
     */
    public function actionExamineGoodsSku(){
        $goods_list_edit = new GoodsListEdit();
        $goods_sale_edit = new GoodsSaleEdit();
        $goods_sale = new GoodsSale();
        $goods_list = new GoodsList();
        $data = Yii::$app->request->post();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $is_examine = $data['status'];
            $id = $data['id'];
            $oper = $goods_sale->getCreator();
            $operTime = date('Y-m-d H:i:s');
            $change = [];
            switch ($is_examine){
                case '3':
                    $sale_edit = $goods_sale_edit::find()->where('id=:id',[':id'=>$id])->asArray()->one();
                    if ($sale_edit['main_goods_id']){
                        $list = GoodsList::find()->where(['main_goods_id'=>$sale_edit['main_goods_id']])->asArray()->one();
                        if ($list['sku']){
                            $list_edit = GoodsListEdit::find()->where(['main_goods_id'=>$sale_edit['main_goods_id']])->asArray()->one();
                            if ($list_edit['id'] && $list_edit['sku'] != $list['sku']){
                                unset($list['id'],$list['creator'],$list['create_time']);
                                $list['is_examine'] = $is_examine;
                                $list_edit_res = GoodsListEdit::updateAll($list,['id'=>$list_edit['id']]);
                                if (!$list_edit_res){
                                    throw new \Exception('审核状态修改失败');
                                }
                            }
                        }
                        $sale = $goods_sale::find()->where(['sku'=>$sale_edit['sku']])->asArray()->one();
                        unset($sale['id'],$sale['creator'],$sale['create_time']);
                        $change = $sale;
                    }
                case '2':
                    $change['is_examine'] = $is_examine;
                    $change['editor'] = $oper;
                    $change['edit_time'] = $operTime;
                    break;
            }
            $res = $goods_sale_edit::updateAll($change,['id'=>$id]);
            if (!$res){
                throw new \Exception('审核状态修改失败');
            }
			//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 start
            //审核子商品信息写日志
            $sale_edit = $goods_sale_edit::find()->select(
                'main_goods_id,goods_id,goods_name_cn,sku,marking_img_id,forsale,model,market_price,sale_price,use_flg'
            )->where('id=:id',[':id'=>$id])->asArray()->one();
            $sale = $goods_sale::find()->select(
                'goods_name_cn,sku,marking_img_id,forsale,model,market_price,sale_price,use_flg'
            )->where('goods_id=:goods_id',[':goods_id'=>$sale_edit['goods_id']])->asArray()->one();
            $source_edit = GoodsSourceEdit::find()->where('goods_id='.$sale_edit['goods_id'])->asArray()->all();
            $source = GoodsSource::find()->where('goods_id='.$sale_edit['goods_id'])->asArray()->all();
            $sale_edit['source_url'] = count($source_edit) > 0 ? array_column($source_edit, 'source_url') : '';
            if ($sale){
                $list_edit = $goods_list_edit::find()->select(
                    'goods_id'
                )->where('main_goods_id=:main_goods_id',[':main_goods_id'=>$sale_edit['main_goods_id']])->asArray()->one();
                $list = GoodsList::find()->select(
                    'goods_id'
                )->where('main_goods_id=:main_goods_id',[':main_goods_id'=>$sale_edit['main_goods_id']])->asArray()->one();
                if (!$list || $list_edit['goods_id'] == $list['goods_id']){
                    $sale_edit['is_main'] = $sale['is_main'] = 1;
                }elseif ($list_edit['goods_id'] != $list['goods_id']){
                    if ($list_edit['goods_id'] == $sale_edit['goods_id']){
                        $sale_edit['is_main'] = 1;
                        $sale['is_main'] = 2;
                    }else{
                        $sale_edit['is_main'] = 2;
                        $sale['is_main'] = 1;
                    }
                }
                $sale['source_url'] = count($source) > 0 ? array_column($source, 'source_url') : '';
            }
            $goods_list_edit->writeGoodsLog($sale_edit['main_goods_id'],$sale_edit['goods_id'],8,$sale_edit,$sale,$is_examine);
			//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 end
            $transaction->commit();
            //操作日志
            $this->saveLog($this->service,'SKU商品资料审核', 'EXAMINE' ,'goods_sale_edit id = ' . $id . "\r\n" . \yii\helpers\Json::encode($change));

            $this->retJson("操作成功",200);
        } catch (\Exception $e) {
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:SKU商品资料审核失败 ' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
            $transaction->rollBack();
        }
    }

    /**
     * 商品预览
     * @return string
     */
    public function actionGoodsPreview(){
        try {
            $this->layout = 'main_pro';
            $sale_model = new GoodsSaleEdit();
            $redis = new redisHelper();
            $memberInfo = $redis->getLoginMasterInfo();
            $list_edit_model = new GoodsListEdit();
            $relation_model = new GoodsRelation();
            $data = Yii::$app->request->get();
            if ($data['type'] == '1'){
                $goods_list = GoodsListEdit::findOne($data['id']);
                if (!$goods_list['goods_id']){
                    echo '子商品不存在';die;
                }
                $goodsId = $goods_list['main_goods_id'];
            }elseif ($data['type'] == '2'){
                $goods_sale = GoodsSaleEdit::findOne($data['id']);
                if (!$goods_sale['goods_id']){
                    echo '子商品不存在';die;
                }
                $goodsId = $goods_sale['main_goods_id'];
            }
            $_GET['goods_id'] = $goodsId;
            //获取主商品信息
            if(!$main_list = $list_edit_model->getMainGoodsListByGoodsId($goodsId)){
                throw new \Exception('找不到商品信息');
            }
            //是否加入心愿单
            $main_list['is_collection'] = $this->isCollection($main_list['main_goods_id']) ? 1: 0;
            //增加浏览次数
            $list_edit_model::updateAllCounters(['views'=>1],['main_goods_id'=> $main_list['main_goods_id']]);
            //相关搭配
            $list_edit_id = $list_edit_model->getGoodsListId($main_list['goods_id']);
            $group_main_id_list = $relation_model->getGoodsGroupList($list_edit_id);
            $group_goods_list = $list_edit_model->getMainGoodsList($group_main_id_list);
            if(!empty($group_goods_list)){
                $group_goods_list = $this->getFullGoodsList($group_goods_list);
            }
            //商品资源文件
            $source_model = new GoodsSourceEdit();
            $source_list = $source_model->getSourceList($main_list['goods_id']);
            //分享二维码链接
            $qrcode_url = tools::getWechatUrl($_SERVER,Yii::$app->params['wechat_url_logo']);
            
            //操作日志
            $this->saveLog($this->service,'商品预览', 'PREVIEW' ,'goods_id = ' . $goodsId );
            return $this->render('goods-detail',[
                'qrcode_url'	=>$qrcode_url,						//分享二维码链接
                'source_list'	=>json_encode($source_list,true),	//主商品资源
                'main_list'		=>$main_list,						//主商品信息
                'group_goods_list'=>$group_goods_list,               //相关搭配
                'memberInfo'  => $memberInfo
            ]);
        } catch (\Exception $e) {
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:商品预览 失败 ' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            throw new NotFoundHttpException($e->getMessage());
        }
    }
    
    public function actionSpecList(){
        $specId				= (int)Yii::$app->request->post('spec','');
        $specColorId		= (int)Yii::$app->request->post('spec_color','');
        $mainGoodsId		= (int)Yii::$app->request->post('main_goods_id','');
        
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        try{
            if(!$mainGoodsId){
                throw new \Exception('网络开小车，请稍后');
            }
            
            if(!$specId && !$specColorId){
                throw new \Exception('参数错误，请重试');
            }
            
            //查询主商品信息
            $main_model = new GoodsListEdit();
            if(!$main_list = $main_model->getMainGoodsListByGoodsId($mainGoodsId)){
                throw new \Exception('找不到商品信息');
            }
            
            //获取商品的规格 todo
            $spec	 	= GoodsSaleEdit::getGoodsSaleInfo($mainGoodsId,0,0);
            
            //获取商品对应规格的颜色
            $specColor  		=GoodsSaleEdit::getIdenticalMainGoods($mainGoodsId,$specId,0);
            
            $needsArray	= array_column($specColor,'spec_color');
            
            if (count($needsArray) == 0){
                throw new \Exception('找不到商品信息');
            }
            //如果选择颜色没有对应的规格则
            if(!in_array($specColorId,$needsArray)){
                $specColorId = $needsArray[0];
            }
            
            //获取商品的详情
            $nowGoodsSale =GoodsSaleEdit::getIdenticalMainGoods($mainGoodsId,$specId,$specColorId);
            
            if(1<count($nowGoodsSale) ||!$nowGoodsSale){
                throw new \Exception('当前商品找不到，请稍后重试');
            }
            return [
                'code'=>200,
                'msg'=>'',
                'data'=>[
                    'spec'		=>$spec,
                    'specColor'	=>$specColor,
                    'nowGoodsSale'	=>$nowGoodsSale,
                ]
            ];
        }catch (\Exception $e){
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            return [
                'code'=>$e->getCode(),
                'msg'=>$e->getMessage(),
                'data'=>[]
            ];
        }
    }
    
    //获取优惠券
    public function actionGetCoupon(){
        $data = Yii::$app->request->post();
        $redis = new redisHelper();
        $memberInfo = $redis->getLoginMasterInfo();
        $sale_list = array();
        $sale_model = new GoodsSaleEdit();
        $main_model = new GoodsListEdit();
        //分类id
        $main_list = $main_model::find()->where(['main_goods_id'=>$data['main_goods_id']])->select('genre_type')->asArray()->one();
        $sku_list = $sale_model->getGoodsIdList($data['main_goods_id'],$data['spec'],$data['spec_color']);
        //获取优惠券
        $coupon_model = new getCoupon();
        $co_list = $coupon_model->getCouponData($sku_list,[$main_list['genre_type']]);
        $co_list = json_decode($co_list,true);
        $list = [];
        if($co_list['code'] == 200){
            $list = $co_list['data'];
            //             if (count($co_list['data']) > 0){
            //                 $coupon_receive = [];
            //                 if (tools::arrayHasValue($memberInfo,'id')){
            //                     $coupon_ids = array_column($co_list['data'], 'id');
            //                     $where_coupon = ['and',['in','coupon_id',$coupon_ids],['cust_master_id'=>$memberInfo->id]];
            //                     $coupon_receive = CouponReceive::find()->select('coupon_id')->where($where_coupon)->asArray()->all();
            //                     $coupon_receive = count($coupon_receive) > 0 ? array_combine(array_column($coupon_receive, 'coupon_id'), $coupon_receive) : [];
            //                 }
            //                 foreach ($co_list['data'] as $co_val){
            //                     if (count($coupon_receive) > 0){
            //                         if (!tools::arrayHasValue($coupon_receive,$co_val['id'])){
            //                             $co_val['is_receive'] = false;
            //                         }else{
            //                             $co_val['is_receive'] = true;
            //                         }
            //                     }else{
            //                         $co_val['is_receive'] = false;
            //                     }
            //                     $list[] = $co_val;
            //                 }
            //             }
        }else{
            $this->retJson($co_list['message'],500);
        }
        $this->retJson($list,200);
    }
    
    //整合颜色规格和是否加入心愿单
    public function getFullGoodsList($main_goods_list){
        //是否已经加入心愿单
        $master_favorite_goods_id = $this->getMasterFavorite();
        
        //$sale_model = new GoodsSale();
        //$goods_list = $sale_model->getMainImage($main_goods_list);
        
        //获取品牌信息
        $brand_model = new GoodsBrand();
        $brand_id = array_column($main_goods_list,'brand_id');
        $brand = $brand_model->getBrandListById($brand_id);
        $brand_list = array();
        foreach($brand as $value){
            $brand_list[$value['id']] = $value;
        }
        foreach($main_goods_list as &$main){
            //$main['goods_color_list'] = empty($goods_list[$main['main_goods_id']]) ? array() : $goods_list[$main['main_goods_id']];
            $main['brand_icon'] = helps\tools::arrayHasValue($brand_list,$main['brand_id']) ? $brand_list[$main['brand_id']]['country_icon'] : '';
            $main['brand_country_name'] = helps\tools::arrayHasValue($brand_list,$main['brand_id']) ? $brand_list[$main['brand_id']]['country_name'] : '';
            if(!empty($master_favorite_goods_id) && in_array($main['main_goods_id'],$master_favorite_goods_id)){
                $main['is_collection'] = 1;
            }else{
                $main['is_collection'] = 0;
            }
        }
        
        return $main_goods_list;
    }
    
    //获取用户心愿单
    public function getMasterFavorite(){
        $master_favorite_goods_id = array();
        $master_info = \common\helps\tools::getloginMasterInfo();
        if(!empty($master_info)){
            $master_favorite = CustFavorite::find()->where(['cust_id'=>$master_info->id])->select('main_goods_id')->asArray()->all();
            if(!empty($master_favorite)){
                $master_favorite_goods_id = array_column($master_favorite,'main_goods_id');
            }
        }
        
        return $master_favorite_goods_id;
    }
    
    //判断商品是否收藏
    public function isCollection($main_goods_id){
        $is_login = helps\tools::isLogin();
        if($is_login){
            $master_info = \common\helps\tools::getloginMasterInfo();
            $master_favorite = CustFavorite::find()->where(['cust_id'=>$master_info->id,'main_goods_id'=>$main_goods_id])->select('main_goods_id')->asArray()->one();
            if(!empty($master_favorite)){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
    public function actionGetSpecData(){
        $model = new GoodsSaleEdit();
        $data = Yii::$app->request->post();
        $goods_spec_array = array();
        if(!empty($data['select_goods_id'])){
            //获取主商品信息
            $where = ['id'=>$data['select_goods_id']];
            $main_goods_list = GoodsListEdit::find()->where($where)->select('id,main_goods_id')->asArray()->one();
            $where_sql = 'main_goods_id='.$main_goods_list['main_goods_id'].' and use_flg=1';
            $goods_spec = GoodsSpecRelation::find()->select('spec_id,spec_group_id,spec_val,spec_type')->where($where_sql)->asArray()->all();
			$goods_spec = array_combine(array_column($goods_spec, 'spec_id'), $goods_spec);
            $goods_spec_arr = $goods_spec_com = [];
				if (is_array($goods_spec) && count($goods_spec) > 0)foreach ($goods_spec as $goods_spec_val){
                $goods_spec_array[$goods_spec_val['spec_type']][] = $goods_spec_val;
                $goods_spec_arr[$goods_spec_val['spec_group_id']][] = $goods_spec_val['spec_id'];
            }
            //$goods_spec_com = array_merge($goods_spec_arr);
			//处理可组合的数量
			$goods_spec_array['can_add_count'] 			= 0;
			if(tools::arrayHasValue($goods_spec_array,GoodsSpecGroup::TYPE_ONE) && tools::arrayHasValue($goods_spec_array,GoodsSpecGroup::TYPE_TWO) ){
				$goods_spec_array['can_add_count'] = count($goods_spec_array[GoodsSpecGroup::TYPE_ONE])*count($goods_spec_array[GoodsSpecGroup::TYPE_TWO]);
			}
// 			$goods_spec = GoodsSpecRelation::find()->select('spec_id,spec_group_id,spec_val,spec_type')->where(
// 			    'main_goods_id=:main_goods_id and use_flg=1',[':main_goods_id'=>$data['main_goods_id']]
// 		    )->asArray()->all();
// 		    $goods_spec = array_combine(array_column($goods_spec, 'spec_id'), $goods_spec);
// 		    $goods_spec_arr = $goods_spec_com = [];
// 		    if (is_array($goods_spec) && count($goods_spec) > 0)foreach ($goods_spec as $goods_spec_val){
// 		        $goods_spec_array[$goods_spec_val['spec_type']][] = $goods_spec_val;
// 		        $goods_spec_arr[$goods_spec_val['spec_group_id']][] = $goods_spec_val['spec_id'];
// 		    }
		    $goods_spec_com = array_merge($goods_spec_arr);
		    $result_2 = tools::arrayHasValue($goods_spec_com,0) ? $goods_spec_com[0] : [];
		    $new_result = [];
		    for($i=1;$i<count($goods_spec_com);$i++){
		        $size= count($result_2);
		        for($j=0;$j<$size;$j++){
		            //遍历要进行组合的数组
		            for($k=0;$k<count($goods_spec_com[$i]);$k++){
		                //把组合的字符串放入到结果数组最后一个成员中
		                //这里使用下标0是因为当这个下标0组合完毕之后就没有用了，在下面我们要移除掉这个成员
		                $result_2[] = [$result_2[0],$goods_spec_com[$i][$k]];
		                $new_result[] = $result_2[0].'-'.$goods_spec_com[$i][$k];
		            }
		            //当第一个成员组合完毕，删除这第一个成员
		            array_shift($result_2);
		        }
		    }
		    //获取已添加的规格;
		    $goods_sale = GoodsSaleEdit::find()->select('spec,spec_color')->where(
		        'main_goods_id=:main_goods_id',[':main_goods_id'=>$main_goods_list['main_goods_id']]
	        )->asArray()->all();
	        $goods_sale_arr = [];
	        if (is_array($goods_sale) && count($goods_sale) > 0)foreach ($goods_sale as $goods_sale_val){
	            $goods_sale_arr[] = $goods_sale_val['spec'].'-'.$goods_sale_val['spec_color'];
	            $goods_sale_arr[] = $goods_sale_val['spec_color'].'-'.$goods_sale_val['spec'];
	        }
	        //所有规格减去已添加的规格等于闲用规格，如果闲用规格大于等于1则可以添加子商品否则报错
	        if (is_array($new_result) && count($new_result) > 0)foreach ($new_result as $num=>$new_result_val){
	            if (in_array($new_result_val, $goods_sale_arr)){
	                unset($new_result[$num]);
	            }
	        }
	        $added_sku = tools::arrayHasValue($data,'added_sku') ? $data['added_sku'] : [];
	        if (count($added_sku) > 0)foreach ($added_sku as $added_sku_val){
	            if (in_array($added_sku_val, $new_result)){
	                //未完成
	            }
	        }
	        if (count($new_result) == 0){
	            $this->retJson('已达到规格组合的最大量',500);
	        }else{
	            $new_result = array_merge($new_result);
	            $goods_spec_array['can_add_spec'] = $new_result[0];
	        }
        }
        //相关参数   http://datatables.club/manual/server-side.html
        $this->retJson($goods_spec_array,200);
    }
    
    //获取商品资源文件列表
    public function actionSourceList(){
        $data = Yii::$app->request->post();
        $spec_color = empty($data['spec_color']) ? 0 : $data['spec_color'];
        $main_model = new GoodsSaleEdit();
        $source_model = new GoodsSourceEdit();
        $goods_id = $main_model->getGoodsId($data['main_goods_id'],$data['spec'],$spec_color);
        $source_list = $source_model->getSourceList($goods_id);
        $this->retJson($source_list,200);
    }
    
    //获取促销列表
    public function actionSaleList(){
        $data = Yii::$app->request->post();
        $sale_list = array();
        $sale_model = new GoodsSaleEdit();
        $main_model = new GoodsListEdit();
        //分类id
        $main_list = $main_model::find()->where(['main_goods_id'=>$data['main_goods_id']])->select('category_step1')->asArray()->one();
        $sku_list = $sale_model->getSkuList($data['main_goods_id'],$data['spec'],$data['spec_color']);
        
        $activity_model = new helps\getActivityMessage();
        $cx_list = $activity_model->getActivityMessageData($sku_list,[$main_list['category_step1']]);
        $cx_list = json_decode($cx_list,true);
        if($cx_list['code'] == 200){
            $sale_list = $cx_list['data'];
        }
        $this->retJson($sale_list,200);
    }
    
    //添加子sku时判断是否有闲用规格添加
    public function actionAddSkuVerification(){
        $data = Yii::$app->request->post();
        //获取所有规格
        $data['main_goods_id'] = '11831';
        $goods_spec = GoodsSpecRelation::find()->select('spec_id,spec_group_id,spec_val,spec_type')->where(
            'main_goods_id=:main_goods_id and use_flg=1',[':main_goods_id'=>$data['main_goods_id']]
        )->asArray()->all();
        $goods_spec = array_combine(array_column($goods_spec, 'spec_id'), $goods_spec);
        $goods_spec_arr = $goods_spec_com = [];
        if (is_array($goods_spec) && count($goods_spec) > 0)foreach ($goods_spec as $goods_spec_val){
            $goods_spec_array[$goods_spec_val['spec_type']][] = $goods_spec_val;
            $goods_spec_arr[$goods_spec_val['spec_group_id']][] = $goods_spec_val['spec_id'];
        }
        $goods_spec_com = array_merge($goods_spec_arr);
        $result_2 = tools::arrayHasValue($goods_spec_com,0) ? $goods_spec_com[0] : [];
        $new_result = [];
        for($i=1;$i<count($goods_spec_com);$i++){
            $size= count($result_2);
            for($j=0;$j<$size;$j++){
                //遍历要进行组合的数组
                for($k=0;$k<count($goods_spec_com[$i]);$k++){
                    //把组合的字符串放入到结果数组最后一个成员中
                    //这里使用下标0是因为当这个下标0组合完毕之后就没有用了，在下面我们要移除掉这个成员
                    $result_2[] = [$result_2[0],$goods_spec_com[$i][$k]];
                    $new_result[] = $result_2[0].'-'.$goods_spec_com[$i][$k];
                }
                //当第一个成员组合完毕，删除这第一个成员
                array_shift($result_2);
            }
        }
        //获取已添加的规格;
        $goods_sale = GoodsSaleEdit::find()->select('spec,spec_color')->where(
            'main_goods_id=:main_goods_id and use_flg=1',[':main_goods_id'=>$data['main_goods_id']]
        )->asArray()->all();
        $goods_sale_arr = [];
        if (is_array($goods_sale) && count($goods_sale) > 0)foreach ($goods_sale as $goods_sale_val){
            $goods_sale_arr[] = $goods_sale_val['spec'].'-'.$goods_sale_val['spec_color'];
            $goods_sale_arr[] = $goods_sale_val['spec_color'].'-'.$goods_sale_val['spec'];
        }
        //所有规格减去已添加的规格等于闲用规格，如果闲用规格大于等于1则可以添加子商品否则报错
        if (is_array($new_result) && count($new_result) > 0)foreach ($new_result as $num=>$new_result_val){
            if (in_array($new_result_val, $goods_sale_arr)){
                unset($new_result[$num]);
            }
        }
        if (count($new_result) == 0){
            $this->retJson('已达到规格组合的最大量',500);
        }else{
            $new_result = array_merge($new_result);
            $result = explode('-', $new_result[0]);
            $this->retJson($result,200);
        }
    }
    //add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 start
    public function actionGoodsLog(){
        $data = Yii::$app->request->get();
        return $this->render('goods-log',['id'=>intval($data['id']),'goods_type_log'=>$GLOBALS['GOODS_LOG_TYPE']]);
    }
    
    public function actionSearchGoodsLog(){
        $data = Yii::$app->request->post();
        $id = $data['id'];
        $reservationtime = $data['reservationtime'];
        $field = trim($data['field']);
        $goods_id = trim($data['goods_id']);
        $page = $data['paging'];
        $sql = 'SELECT l.* FROM `j_goods_log` AS l LEFT JOIN `j_goods_list_edit` AS e ON l.main_goods_id=e.main_goods_id WHERE l.main_goods_id='.$id ;
        if ($reservationtime){
            $reservationtime_arr = explode(' - ', $reservationtime);
            if (count($reservationtime_arr) == 2){
                $reservationtime_arr[0] = date('Y-m-d',strtotime($reservationtime_arr[0]));
                $reservationtime_arr[1] = date('Y-m-d',strtotime($reservationtime_arr[1])+86400);
                $sql .= ' AND l.oper_time BETWEEN "'.$reservationtime_arr[0].'" AND "'.$reservationtime_arr[1].'"';
            }
        }
//         if ($goods_name_cn){
//             $sql .= ' AND e.goods_name_cn like "%'.$goods_name_cn.'%"';
//         }
        if ($field){
            $sql .= ' AND l.new_data like "%'.$field.'%"';
        }
        if ($goods_id){
            $sql .= ' AND l.goods_id='.$goods_id;
        }
        $rows_perpage = 10;
        $page = ($page - 1) * $rows_perpage;
        $sql .= ' ORDER BY oper_time DESC LIMIT '.$page.','.$rows_perpage;
        $goods_log = GoodsLog::findBySql($sql)->asArray()->all();
        $this->retJson($goods_log, 200);
    }
	//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 end
}